package com.bridgetree.jubaocrm.ui.project;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.Interviews;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;
/**
 *外出申请/交流记录
 */
@SuppressLint("SimpleDateFormat")
public class XMChildApplyRecordActivity extends Activity {
	private final String TAG ="XMChildApplyRecordActivity";
	private Context mContext;
	private PullToRefreshListView xm_of_lv = null;
	private ListView actualListView1 = null;
	private int scrollTopBottom =0;//top,0;bottom,1
	private XMChildApplyRecordAdapter mXMChildApplyRecordAdapter = null;
	public Projects mProjects;
	private List<Interviews> interviews;
	private int page = 1;
	private String  Topdate  ="";
	private String  Bottomdate  ="";
	private boolean overState =false;//结束标志
	private String user_id =""; 
	private String token ="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xm_apply_record);
		mContext=this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}

		interviews = new ArrayList<Interviews>();
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		
		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("my_projects");
		}

		findViewById(R.id.xm_ar_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		xm_of_lv=(PullToRefreshListView)findViewById(R.id.xm_ar_lv);
		xm_of_lv.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if(scrollTopBottom == 1){
					if(!overState){
						page++;
					}
					SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd   hh:mm:ss");     
					Topdate = sDateFormat.format(new java.util.Date());  
					if(mProjects!=null){
						getApplyRecordData(page);
					}
				}else if(scrollTopBottom==0){
					interviews = new ArrayList<Interviews>();
					page = 1;
					overState=false;
					SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd   hh:mm:ss");     
					Bottomdate = sDateFormat.format(new java.util.Date());  
					if(mProjects!=null){
						getApplyRecordData(page);
					}
				}
//				Log.e("wop"," 档案    page = "+page);
			}
		});

		xm_of_lv.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if(firstVisibleItem+visibleItemCount == totalItemCount){
					scrollTopBottom=1;
					if(xm_of_lv!=null){
						xm_of_lv.setUpdatatime(Bottomdate);
					}
				}else if(firstVisibleItem == 0){
					scrollTopBottom = 0;
					if(xm_of_lv!=null){
						xm_of_lv.setUpdatatime(Topdate);
					}
				}
			}
		});
		actualListView1 = xm_of_lv.getRefreshableView();

		if(mProjects!=null){
			getApplyRecordData(1);
		};

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 10000 && data!=null){
			int index=data.getIntExtra("index", -1);
			if(resultCode ==0x001){
				//签到和补录
				String address =data.getStringExtra("address");
				String editTime = data.getStringExtra("editTime");
				interviews.get(index).setSigned_where(address);
				interviews.get(index).setSigned_time(editTime);
				interviews.get(index).setContent(data.getStringExtra("record"));
				mXMChildApplyRecordAdapter.notifyDataSetChanged();
			}else if(resultCode ==0x002){
				//只补录
				interviews.get(index).setContent(data.getStringExtra("record"));
			}else if(resultCode ==0x003){
				//之签到
				String address =data.getStringExtra("address");
				String editTime = data.getStringExtra("editTime");
				interviews.get(index).setSigned_where(address);
				interviews.get(index).setSigned_time(editTime);
				mXMChildApplyRecordAdapter.notifyDataSetChanged();
				Log.d("XMChildApplyRecordActivity", "address:"+address+"editTime");
			}
		}
	}

	private void getApplyRecordData(int pageIndex) {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog=ProgressDialogUtil.show(mContext);
			String URL = Network.API_DOMAIN+"/interviews?project_id="+mProjects.getProject_id()
			+"&user_id="+user_id+"&token="+token+"&validation="
			+CRMUserBaseInfo.kValication+"&page="+pageIndex;

			//final ProgressDialog progressDialog = ProgressDialog.show(this, "网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {  
						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("外出申请/交流记录 response="+response);  
//							if (progressDialog.isShowing()&&progressDialog!=null) {  
//								progressDialog.dismiss();  
//							}

							try {
								if (!response.isNull("interviews")) {
									String interview = response.getString("interviews");
									if (interview.equals("[]")) {
										overState=true;
										Toast.makeText(mContext, "已经到最后了~", Toast.LENGTH_SHORT).show();
									}else{
										org.json.JSONArray jsonArr;
										jsonArr = response.getJSONArray("interviews");
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr.length(); i++) {
												Interviews mInterviews = new Interviews();
												JSONObject jsonObj2 = jsonArr.getJSONObject(i);
												if (!jsonObj2.isNull("content")) {
													String content = jsonObj2.getString("content");
													mInterviews.setContent(content);
												}
												if (!jsonObj2.isNull("people_of_us")) {
													String people_of_us = jsonObj2.getString("people_of_us");
													mInterviews.setPeople_of_us(people_of_us);
												}
												if (!jsonObj2.isNull("created_user_id")) {
													String created_user_id = jsonObj2.getString("created_user_id");
													mInterviews.setCreated_user_id(created_user_id);
												}
												if (!jsonObj2.isNull("address")) {
													String address = jsonObj2.getString("address");
													mInterviews.setAddress(address);
												}
												if (!jsonObj2.isNull("people_of_client")) {
													String people_of_client = jsonObj2.getString("people_of_client");
													mInterviews.setPeople_of_client(people_of_client);
												}
												if (!jsonObj2.isNull("signed_time")) {
													String signed_time = jsonObj2.getString("signed_time");
													mInterviews.setSigned_time(signed_time);
												}
												if (!jsonObj2.isNull("longitude")) {
													String longitude = jsonObj2.getString("longitude");
													mInterviews.setLongitude(longitude);
												}
												if (!jsonObj2.isNull("interview_type")) {
													String interview_type = jsonObj2.getString("interview_type");
													mInterviews.setInterview_type(interview_type);
												}
												if (!jsonObj2.isNull("time_line")) {
													String time_line = jsonObj2.getString("time_line");
													mInterviews.setTime_line(time_line);
												}
												if (!jsonObj2.isNull("latitude")) {
													String latitude = jsonObj2.getString("latitude");
													mInterviews.setLatitude(latitude);
												}
												if (!jsonObj2.isNull("signed_where")) {
													String signed_where = jsonObj2.getString("signed_where");
													mInterviews.setSigned_where(signed_where);
												}
												if (!jsonObj2.isNull("is_edited")) {
													boolean is_edited = Boolean.valueOf(jsonObj2.getString("is_edited"));
													mInterviews.setIs_edited(is_edited);
												}
												if (!jsonObj2.isNull("interview_id")) {
													String interview_id = jsonObj2.getString("interview_id");
													mInterviews.setInterview_id(interview_id);
												}
												interviews.add(mInterviews);
											}
										}
										mXMChildApplyRecordAdapter = new XMChildApplyRecordAdapter(XMChildApplyRecordActivity.this,interviews,mProjects);
										actualListView1.setAdapter(mXMChildApplyRecordAdapter);
									}
									if(mXMChildApplyRecordAdapter!=null)
										mXMChildApplyRecordAdapter.notifyDataSetChanged();
									
									if (xm_of_lv != null) {
										xm_of_lv.onRefreshComplete();
									}
								}
								
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														mLoginError.setDesc(desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					},
					new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) { 
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");  
						}  
					});  
			requestQueue.add(jsonObjectRequest); 
		}
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}


	class XMChildApplyRecordAdapter extends BaseAdapter {
		private Context mContext;
		private List<Interviews> DrugstoreDataList = null;
		private Projects mProjects;
		private LayoutInflater listContainer; // 视图容器

		public final class ListItemView { // 自定义控件集合
			public RelativeLayout RelativeLayouts; 
			public TextView xm_ar_item_time; 
			public ImageView xm_ar_item_iv_foot; 
			public TextView xm_ar_item_people; 
		}

		public XMChildApplyRecordAdapter(Context mContext, List<Interviews> interviews,Projects mProjects) {
			this.mContext = mContext;
			this.DrugstoreDataList = interviews;
			this.mProjects = mProjects;
			listContainer = (LayoutInflater) mContext
			.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			if (DrugstoreDataList != null) {
				return DrugstoreDataList.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return DrugstoreDataList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ListItemView listItemView = null;
			if (convertView == null) {
				listItemView = new ListItemView();
				// 获取list_item布局文件的视图
				convertView = listContainer.inflate(R.layout.xm_apply_record_item, null);
				// 获取控件对象
				listItemView.RelativeLayouts = (RelativeLayout) convertView.findViewById(R.id.RelativeLayouts);
				listItemView.xm_ar_item_iv_foot= (ImageView) convertView.findViewById(R.id.xm_ar_item_iv_foot);
				listItemView.xm_ar_item_time = (TextView) convertView.findViewById(R.id.xm_ar_item_time);
				listItemView.xm_ar_item_people = (TextView) convertView.findViewById(R.id.xm_ar_item_people);
				// 设置控件集到convertView
				convertView.setTag(listItemView);
			} else {
				listItemView = (ListItemView) convertView.getTag();
			}
			String line1 = (String) DrugstoreDataList.get(position).getTime_line();
			
			String line2 =(String) DrugstoreDataList.get(position).getInterview_type()+
			"-"+(String) DrugstoreDataList.get(position).getPeople_of_us();
			listItemView.xm_ar_item_people.setText(line2);
			
			String interview_type = DrugstoreDataList.get(position).getInterview_type();
			String time_line = DrugstoreDataList.get(position).getTime_line();
			Date newDate = strToDate(time_line);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			String dateString = formatter.format(newDate);
			listItemView.xm_ar_item_time.setText(dateString);
			String nowDate = getNows();
			boolean bijiao = false;
			//比较
			if(time_line.compareTo(nowDate)>0){//>
				bijiao = true;
			}else{
				bijiao = false;
			}
//			if (Math.abs(((nowDate.getTime() - newDate.getTime()) / (24 * 3600 * 1000))) > 1) {
//				System.out.println("大于1天");
//				 bijiao = true;
//			} else {
//				System.out.println("小于1天");
//				 bijiao = false;
//			}
			
//			boolean is_edited = Boolean.valueOf(DrugstoreDataList.get(position).getIs_edited());
			String signed_time = DrugstoreDataList.get(position).getSigned_time();
			if(signed_time.equals("")){
				if(interview_type.equals("面谈")){
					if(bijiao){
						listItemView.xm_ar_item_iv_foot.setImageResource(R.drawable.check2x);
					}else{
						listItemView.xm_ar_item_iv_foot.setImageResource(R.drawable.overcheckin2x);
					}
				}else if(interview_type.equals("非面谈")){
//					listItemView.xm_ar_item_iv_foot.setImageResource(R.drawable.checkedin2x);
					listItemView.xm_ar_item_iv_foot.setVisibility(View.GONE);
				}else {
					listItemView.xm_ar_item_iv_foot.setImageResource(R.drawable.checkedin2x);
				}
			}else{
				listItemView.xm_ar_item_iv_foot.setImageResource(R.drawable.checkedin2x);
			}
		

			listItemView.RelativeLayouts.setOnClickListener(new
					OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent=null;
					Bundle bundle=null;
					intent = new Intent(mContext, XMChildApplyRecordItemActivity.class);
					bundle = new Bundle();
					bundle.putInt("index", position);
					bundle.putSerializable("Interviews", DrugstoreDataList.get(position));
					bundle.putSerializable("mProjects", mProjects);
					intent.putExtras(bundle);
					((Activity)mContext).startActivityForResult(intent, 10000);
				}
			});
			return convertView;
		}
		
		/**
		  * 将短时间格式字符串转换为时间 yyyy-MM-dd 
		  * 
		  * @param strDate
		  * @return
		  */
		public Date strToDate(String strDate) {
		  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		  ParsePosition pos = new ParsePosition(0);
		  Date strtodate = formatter.parse(strDate, pos);
		  return strtodate;
		}
		
		/**
		  * 得到现在时间
		  * 
		  * @return
		  */
		public Date getNow() {
		  Date currentTime = new Date();
		  return currentTime;
		}
		
		public String getNows() {
			  Date currentTime = new Date();
			  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			  String dateString = formatter.format(currentTime);
			  return dateString;
			}

		

	}
	
}